package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserIdHolder;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * bug
     * 两次点了同一个菜, 但是口味不一样, 第二次选择的口味不会保存  没错 前端逻辑就是这样的
     * 所有给出的口味选项每类 必须且只能 选一个, 忌口 我可以不选或多选吗? 不可以
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        log.info("购物车数据:{}", shoppingCart);
        //从本地线程中得到 用户id
        //同一个 用户id 可能对应 多个 购物车Id
        Long userId = UserIdHolder.get();
        shoppingCart.setUserId(userId);
        //一个购物车里 可能装菜品也可能装套餐, 所以 dishId setmealId 只会有一个
        Long dishId = shoppingCart.getDishId();

        LambdaQueryWrapper<ShoppingCart> shoppingCartLQW = new LambdaQueryWrapper<>();
        shoppingCartLQW.eq(ShoppingCart::getUserId, userId);
//        SFunction<ShoppingCart, Long> getDishOrSetmealId =
//                dishId != null ? (ShoppingCart::getDishId) : (ShoppingCart::getSetmealId);
//        shoppingCartLQW.eq(getDishOrSetmealId, dishId);
        if (dishId != null) {
            //添加到购物车的是菜品
            shoppingCartLQW.eq(ShoppingCart::getDishId, dishId);
        } else {
            //添加到购物车的是套餐
            shoppingCartLQW.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        //查询当前菜品或者套餐是否在购物车中
        ShoppingCart oneShoppingCart = shoppingCartService.getOne(shoppingCartLQW);
        if (oneShoppingCart != null) {
            //修改 : 如果已经存在，就在原来数量基础上加一
            oneShoppingCart.setNumber(oneShoppingCart.getNumber() + 1);
            shoppingCartService.updateById(oneShoppingCart);
            //返回添加的购物车数据
            return R.success(oneShoppingCart);
        } else {
            //添加 : 如果不存在，则添加到购物车，数量默认就是一
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            //返回添加的购物车数据
            return R.success(shoppingCart);
        }
    }

    /**
     * 查看购物车
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        log.info("查看购物车...");
        //从本地线程中得到 用户id 并根据 用户id 到 购物车表中查询
        LambdaQueryWrapper<ShoppingCart> shoppingCartLQW = new LambdaQueryWrapper<>();
        shoppingCartLQW.eq(ShoppingCart::getUserId, UserIdHolder.get());
        List<ShoppingCart> list = shoppingCartService.list(shoppingCartLQW);
        return R.success(list);
    }

    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean() {
        //从本地线程中得到 用户id 并根据 用户id 到 购物车表中清空购物车
        //SQL:delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> shoppingCartLQW = new LambdaQueryWrapper<>();
        shoppingCartLQW.eq(ShoppingCart::getUserId, UserIdHolder.get());
        shoppingCartService.remove(shoppingCartLQW);
        return R.success("清空购物车成功");
    }

    /**
     * 每次减一
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        log.info("购物车数据:{}", shoppingCart);
        Long dishId = shoppingCart.getDishId();
        LambdaUpdateWrapper<ShoppingCart> shoppingCartLUW = new LambdaUpdateWrapper<>();
        shoppingCartLUW.eq(ShoppingCart::getUserId, UserIdHolder.get());
        SFunction<ShoppingCart, Long> getDishOrSetmealId =
                dishId != null ? (ShoppingCart::getDishId) : (ShoppingCart::getSetmealId);
        shoppingCartLUW.eq(getDishOrSetmealId, dishId);
        ShoppingCart oneShoppingCart = shoppingCartService.getOne(shoppingCartLUW);
        oneShoppingCart.setNumber(oneShoppingCart.getNumber() - 1);

        if (oneShoppingCart.getNumber() == 0) {
            // 删除这条记录
            shoppingCartService.removeById(oneShoppingCart);
        } else {

            shoppingCartService.updateById(oneShoppingCart);
        }

      /*  if (dishId != null) {
            //购物车中想要减一的是菜品
            shoppingCartLUW.eq(ShoppingCart::getDishId, dishId);
            ShoppingCart oneShoppingCart = shoppingCartService.getOne(shoppingCartLUW);
            Integer number = oneShoppingCart.getNumber();
            if (number < 1) {
                throw new RuntimeException("不能再减啦");
            } else if (number == 1) {
                // 删除这条记录
                shoppingCartService.removeById(oneShoppingCart);
            } else {
                shoppingCartLUW.set(ShoppingCart::getNumber, (number - 1));
                shoppingCartService.update(shoppingCartLUW);
            }
        } else {
            //购物车中想要减一的是套餐
            shoppingCartLUW.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
            ShoppingCart oneShoppingCart = shoppingCartService.getOne(shoppingCartLUW);
            Integer number = oneShoppingCart.getNumber();
            if (number < 1) {
                throw new RuntimeException("不能再减啦");
            } else if (number == 1) {
                // 删除这条记录
                shoppingCartService.removeById(oneShoppingCart);
            } else {
                shoppingCartLUW.set(ShoppingCart::getNumber, (number - 1));
                shoppingCartService.update(shoppingCartLUW);
            }
        }*/
        return R.success(oneShoppingCart);
    }

}